package MydbQA::Command::Ooe;

use strict;
use warnings;

use base 'MydbQA::Command::Base';

use Carp;
use Getopt::Long;
use Storable qw (dclone);
use HTML::Template;
use List::Util qw(min max sum);

sub run {
      my $self = shift;

      my $variants = $self->ooe->orders($self->sql_builder , $self->tables);
      
      $self->ooe_variants($variants);
      
      #foreach my $num (sort { $a <=> $b } @all_rows_num) {
      #      for (my $i = 0; $i <= $#{$self->{_data}->{ooe}}; $i++) {
      #            next unless $self->{_data}->{ooe}->[$i]->{ooe_q_totalrows} eq $num; 
      #            push @ordered , $self->{_data}->{ooe}->[$i];
      #      }
      #}
      #$self->{_data}->{ooe} = \@ordered;
      
      $self->{html} ? $self->as_html : $self->as_text;
}

sub ooe_variants {
      my ($self , $variants) = @_;
      
      my @all_rows_num;
      for (@$variants) {
            my %temp = ();
                
            my $straight_join_sql = $self->hints->add_straight_join($_);
            $self->explain->explain($straight_join_sql);
            
            my $result = $self->explain->results;
            foreach my $explain_table (@$result) {
                  my $t = $explain_table->{type};
                  if ($t eq 'ALL') {
                        $explain_table->{type_color} = "red";
                  } elsif ($t eq 'index') {
                        $explain_table->{type_color} = "yellow";
                  } elsif ($t =~ /const|system/) {
                        $explain_table->{type_color} = "green";
                  }
            }
            
            $temp{ooe_q} = $straight_join_sql;
            $temp{ooe_q_explain} = $result;
            $temp{ooe_q_totalrows} += $self->explain->total_rows;
                
            push @all_rows_num , $self->explain->total_rows;; 
            push @{$self->{_data}->{ooe}} , \%temp;
      }
      
      my @ordered = ();
      my $min = min @all_rows_num;
      
      @{$self->{_data}->{ooe}} = sort { $a->{ooe_q_totalrows} <=> $b->{ooe_q_totalrows} } @{$self->{_data}->{ooe}};
}

sub as_html {
      my ($self , $data) = @_;
        
      my $tmpl = HTML::Template->new( filename => "../share/tmpl/ooe.html" , die_on_bad_params => 0 );
      $tmpl->param(nohighlight => 1) if $self->{nohighlight};
      $tmpl->param(ooe => $self->{_data}->{ooe});
        
      my $path = $self->{output};
      
      open (FH , "+>$path/analyze_ooe.html") || die print $!;
            print FH $tmpl->output;
      close FH;
        
      print "Ooe report generated in html file: $path/analyze_ooe.html\n"; 
}

sub as_text {
      print "Text report is not implemented yet";
}

1;
